<template>
  <div class="count-button">
    <button class="minus" @click="handleMinus">-</button>
    <input type="number" class="count" :value="value" @change="handleChange($event)">
    <button class="add" @click="handleAdd">+</button>
  </div>
</template>

<script>
export default {
  name: 'CountButton',
  props: {
    value: {
      type: Number,
      default: 0
    },
    maxAmount: {
      type: Number,
      default: 9999
    }
  },
  methods: {
    handleAdd () {
      if (this.value >= this.maxAmount) {
        this.$toast.fail('数目超过库存！')
        return
      }
      this.$emit('input', this.value + 1)
    },
    handleMinus () {
      if (this.value <= 0) {
        this.$toast.fail('购买数目不少于0！')
        return
      }
      this.$emit('input', this.value - 1)
    },
    handleChange (e) {
      if (+e.target.value <= 0) return
      if (+e.target.value !== Number) return
      this.$emit('input', e.target.value)
    }
  }
}
</script>

<style scoped lang="less">
.count-button {
  button {
    border: none;
    width: 30px;
    height: 30px;
  }
  input {
    border: none;
    background-color: rgb(239,239,239);
    width: 40px;
    height: 30px;
    margin: 0 5px;
    text-align: center;
  }
}
</style>
